package com.wtf.service;

import com.wtf.dao.AuthCodeDao;
import com.wtf.pojo.AuthCode;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;

/**
 * @author tengfei wang
 * @version 1.0
 * @date Created in 2020/11/2
 */
@Service
public class CodeServiceImpl implements CodeService {

    private static final Integer STATUS_CORRECT = 0;
    private static final Integer STATUS_ERROR = 1;
    private static final Integer STATUS_EXPIRE = 2;

    @Resource
    private AuthCodeDao authCodeDao;

    @Resource
    private EmailFeignService emailFeignService;

    @Override
    public boolean createCode(String email) {
        // 校验数据库中当前邮箱是否保留的有code，如果有删除
        List<AuthCode> allByEmail = authCodeDao.findAllByEmail(email);
        if (allByEmail.size() > 0) {
            authCodeDao.deleteInBatch(allByEmail);
        }
        //创建新的code数据
        AuthCode authCode = new AuthCode();
        int code = randInt();
        authCode.setCode(code);
        authCode.setEmail(email);
        long cTime = System.currentTimeMillis();
        authCode.setCreateTime(new Date(cTime));
        authCode.setExpireTime(new Date(cTime + (1000 * 60 * 10)));

        boolean isSendSuccess = emailFeignService.sendEmail(email, code);
        if (isSendSuccess) {
            authCodeDao.save(authCode);
            return true;
        }
        return false;
    }

    @Override
    public Integer validCode(String email, Integer code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<? extends AuthCode> ex = Example.of(authCode);
        Optional<? extends AuthCode> optional = authCodeDao.findOne(ex);
        if (!optional.isPresent()) {
            return STATUS_ERROR;
        }

        AuthCode auth = optional.get();
        Date expireTime = auth.getExpireTime();

        // 超过十分钟算过期
        if (System.currentTimeMillis() - expireTime.getTime() > (1000 * 60 * 10)) {
            return STATUS_EXPIRE;
        }

        return STATUS_CORRECT;
    }

    private int randInt() {
        Random rand = new Random();
        return rand.nextInt((999999 - 100000) + 1) + 100000;
    }

}
